/*
 * @Author: zhuxiaoyi
 * @Date: 2024-01-22 17:04:45
 * @LastEditor: zhuxiaoyi
 * @LastEditTime: 2024-08-15 18:07:41
 * @Description:
 */
import { Provide, Inject } from '@midwayjs/core';
import * as fs from 'fs';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Product } from '../entity/product.entity';
import { Repository, Like, SelectQueryBuilder } from 'typeorm';
import { Context } from '@midwayjs/koa';
import { GetProductsDto } from '../dto/ProductDto';

@Provide()
export class ProductService {
    @InjectEntityModel(Product)
    ProductModel: Repository<Product>;
    @Inject()
    ctx: Context;

    async getProductsList(params: GetProductsDto) {
        const queryBuilder: SelectQueryBuilder<Product> = this.ProductModel.createQueryBuilder('product');

        // 添加关键字搜索条件
        if (params.keyword) {
            queryBuilder.where('product.fileName LIKE :keyword', { keyword: `%${params.keyword}%` })
                .orWhere('product.filePath LIKE :keyword', { keyword: `%${params.keyword}%` });
        }

        // 添加类型过滤条件
        if (params.type) {
            queryBuilder.andWhere('product.productType = :type', { type: params.type });
        }

        // 添加分页和排序
        queryBuilder.skip((params.page_index - 1) * params.page_size)
            .take(params.page_size)
            .orderBy('product.create_time', 'DESC'); // 根据实际需求替换字段
            
        const [result, total] = await queryBuilder.getManyAndCount();
        return {
            success: true,
            data: result,
            total,
            message: '成功',
        };
    }


}
